﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace VersionManage.Common
{
    /// <summary>
    /// 网络工具类。
    /// </summary>
    public sealed class WebUtils
    {
        private const string POST = "POST";
        private const string GET = "GET";
        /// <summary>
        /// 响应的 HTTP 内容类型
        /// </summary>
        private const string CONTENTTYPE = "application/x-www-form-urlencoded;charset=utf-8";
        private int _timeout = 100000;

        /// <summary>
        /// 请求与响应的超时时间
        /// </summary>
        public int Timeout
        {
            get { return this._timeout; }
            set { this._timeout = value; }
        }
        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        /// <exception cref="ArgumentNullException">Url为空或POST请求参数为空时抛出异常ArgumentNullException</exception>
        /// <exception cref="DoPostException">自定义异常，Post是引起WebException异常时方法抛出异常DoPostException</exception>
        public string DoPost(string url, string parameters)
        {
            if (System.String.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("Url不能为空！");
            }
            if (System.String.IsNullOrEmpty(parameters))
            {
                throw new ArgumentNullException("POST请求参数不能为空！");
            }
            HttpWebRequest req = null;
            HttpWebResponse rsp = null;
            Encoding encoding = null;
            string result = null;
            try
            {
                req = GetWebRequest(url, POST);
                req.ContentType = CONTENTTYPE;

                byte[] postData = Encoding.UTF8.GetBytes(parameters);
                Stream reqStream = req.GetRequestStream();
                reqStream.Write(postData, 0, postData.Length);
                reqStream.Close();
                LogWrite.WriteLog(req.ToString() + " ,parameters: " + parameters, "DoPost(string url, string parameters)");
                rsp = (HttpWebResponse)req.GetResponse();
                if (rsp.CharacterSet != null)
                {
                    encoding = Encoding.GetEncoding(rsp.CharacterSet);
                }
                else
                {
                    encoding = Encoding.Default;
                }
            }
            catch (Exception e)
            {
                LogWrite.WriteLog(e.ToString(), "URL请求失败：" + url);
                throw;
            }

            result = GetResponseAsString(rsp, encoding);
            return result;
        }
        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        public string DoGet(string url, IDictionary<string, string> parameters)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQuery(parameters);
                }
                else
                {
                    url = url + "?" + BuildQuery(parameters);
                }
            }

            HttpWebRequest req = GetWebRequest(url, "GET");
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            return GetResponseAsString(rsp, encoding);
        }

        private HttpWebRequest GetWebRequest(string url, string method)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = method;
            req.KeepAlive = true;
            req.UserAgent = "Top4Net";
            req.Timeout = this._timeout;
            return req;
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        private string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            StringBuilder result = new StringBuilder();
            Stream stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);

                // 每次读取不大于256个字符，并写入字符串
                char[] buffer = new char[256];
                int readBytes = 0;
                while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
                {
                    result.Append(buffer, 0, readBytes);
                }
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }

            return result.ToString();
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            if (parameters != null)
            {
                bool hasParam = false;

                IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
                while (dem.MoveNext())
                {
                    string name = dem.Current.Key;
                    string value = dem.Current.Value;
                    // 忽略参数名或参数值为空的参数
                    //if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                    //{
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");

                    postData.Append(Uri.EscapeDataString(value == null ? "" : value));
                    hasParam = true;
                    //}
                }
            }

            return postData.ToString();
        }


        /// <summary>
        /// 获得json格式数据
        /// </summary>
        /// <param name="paras"></param>
        /// <returns></returns>
        public static string GetJson(IDictionary<string, string> paras)
        {
            StringBuilder sb = new StringBuilder();
            bool hasParam = false;
            sb.Append("{");

            IEnumerator<KeyValuePair<string, string>> dem = paras.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                {
                    if (hasParam)
                    {
                        sb.Append(",");
                    }

                    sb.Append("\"" + name + "\"");
                    sb.Append(":");
                    sb.Append("\"" + Uri.EscapeDataString(value) + "\"");
                    hasParam = true;
                }
            }
            sb.Append("}");

            return sb.ToString();
        }

    }
}
